<template>
  <div class="home">
    <div class="banner-box">
      <div class="banner-box-top">
        <div class="user-position">
          <i class="user-position-icon"></i>
          <div class="user-position-adress">{{address}}</div>
        </div>
        <div class="search" @click="navigateToSearch">
          <span class="search-icon"></span>
          搜索
        </div>
      </div>
      <swiper
        class="swiper"
        :indicator-dots="indicatorDots"
        :autoplay="autoplay"
        :interval="interval"
        :duration="duration"
      >
        <div v-for="(item,index) in carousel" :key="index">
          <swiper-item>
            <img :src="item.photo_url" class="banner-img"/>
          </swiper-item>
        </div>
      </swiper>
    </div>
    <ScrollX scrollTitle="主题活动" :scrollList="ClassifyList" :callback="selectClassify" />
    <DoubleColumnList :dataList="PartyList" title="人气活动方" :btnFunc="navgateToOrganizer" btnShow="true" btnText="更多活动方" type='organizer' :listFunc="navigaToOrganizerIntro"/>
    <ActivityList v-for="(item,index) in activityList" :key="index" :dataList="item" :itemIndex="index" :callback="navigateToDetail" :keepCallback="keep"/>
  </div>
</template>

<script>
import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js'
import ActivityList from '../../components/activityList.vue'
import ScrollX from '../../components/scrollX.vue'
import DoubleColumnList from '../../components/doubleColumnList.vue'
import { 
  getClassify,
  getActivityList,
  getCarousel,
  postActivityKeep,
  postCancelActivityKeep,
  getPartyList
} from '../../api/index.js'
import { mapState,mapMutation,mapActions } from 'vuex'

export default {
  data () {
    return {
      indicatorDots: true,
      autoplay: true,
      indicatorFlag: true,
      interval: 5000,
      duration: 1000,
      ClassifyList: [], //分类列表
      activityList: [], //首页展示的活动列表
      carousel: [], //轮播图
      limit: 6, //活动条数
      page: 0, //页码
      selectType: 0,// 0为精选列表，2为关键词查询
      keywords: '',// 关键词查询分页用
      reachBottomFlag: true, // 没有数据了不再发送请求
      address: '地区', //获取定位地址
      PartyList: [], //活动方列表
    }
  },
  components: {
    ActivityList,
    ScrollX,
    DoubleColumnList
  },
  onShow(){
    this.getUserPosition();
    this.reqCarousel();
    this.reqClassify();
    this.reqPopularityPartyList();
  },
  onLaunch(){
    this.page= 0;
    this.reachBottomFlag = true;
    // this.reqChoiceList();
  },
  onLoad(option){
    if(option.keywords){
      this.selectKeywords(option.keywords)
    }
  },
  //下拉刷新
  onPullDownRefresh () {
    this.intSelectCity(this.address)
  },
  //上拉加载
  onReachBottom () {
    if(this.reachBottomFlag){
      this.page++;
      // if(this.selectType == 0){
      //   this.reqChoiceList();
      // }else 
      if(this.selectType == 1){
        this.reqSelectCity(this.address)
      }else{
        this.selectKeywords(this.keywords)
      }
    }
  },
  methods: {
    ...mapActions(['_reqUserInfo']),
    //获取轮播图数据
    async reqCarousel(){
      let res = await getCarousel();
      if(res.data.level == "success"){
        let date = res.data.data;
        this.carousel = date;
      }else{
        wx.showToast({
          title: '获取轮播图失败',
          icon: 'none',
          duration: 1000
        })
      }
    }, 
    //获得活动分类数据
    async reqClassify(){
      let res = await getClassify();
      if(res.data.level == "success"){
        let date = res.data.data;
        this.ClassifyList = date;
      }else{
        wx.showToast({
          title: '获取活动分类失败',
          icon: 'none',
          duration: 1000
        })
      }
    },
    //获取首页精选数据
    // async reqChoiceList(){
    //   var userToken = wx.getStorageSync('userToken');
    //   let params = { 
    //     choice: 1,
    //     limit: this.limit,
    //     page: this.page,
    //     user_token: userToken
    //   };
    //   let res = await getActivityList(params);
    //   if(res.data.level == "success"){
    //     let choiceList = res.data.activities;
    //     wx.stopPullDownRefresh()
    //     if(choiceList.length <= 0){
    //       this.reachBottomFlag = false; //如果没有数据了，上拉分页不再发送网络请求
    //     }else{
    //       if(params.page== 0){
    //         this.activityList = choiceList;
    //       }else{
    //         this.activityList = this.activityList.concat(choiceList);
    //       }
    //     }
    //   }else{
    //     wx.showToast({
    //       title: '获取精选数据失败',
    //       icon: 'none',
    //       duration: 1000
    //     })
    //   }
    // },
    //点击触发分类查询
    selectClassify(classify){
      wx.navigateTo({
        url: '/pages/classify/main?ClassifyId='+ classify.id + '&has_secondary='+ classify.has_secondary + '&ClassifyName=' + classify.name
      })
    },
    //关键词查询
    selectKeywords(keywords){
      this.page = 0; //page初始化
      this.selectType == 2;//根据类型判断分页
      this.reachBottomFlag = true;//初始化分页开关
      this.keywords = keywords;
      this.reqSelectKeywords(keywords);
    },
    //获取关键词查询的数据
    async reqSelectKeywords(keywords){
      var userToken = wx.getStorageSync('userToken');
      let params = {
        user_token: userToken,
        keywords: keywords,
        limit: this.limit,
        page: this.page
      };
      let res = await getActivityList(params);
      if(res.data.level == "success"){
        let keywordsActivityList = res.data.activities;
        if(keywordsActivityList.length <= 0){
          this.reachBottomFlag = false; //如果没有数据了，上拉分页不再发送网络请求
        }else{
          if(params.page== 0){
            this.activityList = keywordsActivityList;
          }else{
            this.activityList = this.activityList.concat(keywordsActivityList);
          }
        }
      }else{
        wx.showToast({
          title: '获取活动列表失败',
          icon: 'none',
          duration: 1000
        })
      }
    },
    //跳转到对应活动详情
    navigateToDetail(activityInfo){
      wx.navigateTo({
        url: '/pages/detail/main?id='+activityInfo.id
      })
    },
    //跳转到搜索页
    navigateToSearch(){
      wx.navigateTo({
        url: '/pages/search/main'
      })
    },
    //点击收藏按钮
    keep(activity, index){
      if(activity.is_collection == 2){
        this.reqKeep(activity, index)
      }else{
        this.reqCancelKeep(activity, index)
      }
    },
    //发送收藏请求
    async reqKeep(activity,index){
      var userToken = wx.getStorageSync('userToken');
      let parmas = {
        user_token: userToken,
        activity_id: activity.id
      }
      let res = await postActivityKeep(parmas);
      if(res.data.level == "success"){
        this.activityList[index].is_collection = 1;
        wx.showToast({
          title: '收藏成功',
          icon: 'none',
          duration: 1000
        })
      }else{
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1000
        })
      }
    },
    //发送取消收藏请求
    async reqCancelKeep(activity,index){
      var userToken = wx.getStorageSync('userToken');
      let parmas = {
        user_token: userToken,
        activity_id: activity.id
      }
      let res = await postCancelActivityKeep(parmas);
      if(res.data.level == "success"){
        this.activityList[index].is_collection = 2;
        wx.showToast({
          title: '取消收藏成功',
          icon: 'none',
          duration: 1000
        })
      }else{
        wx.showToast({
          title: '取消收藏失败',
          icon: 'none',
          duration: 1000
        })
      }
    },
    //跳转到随心页面
    navigaToFree(){
      wx.navigateTo({
        url: '/pages/free/main'
      })
    },
    //获取用户当前定位
    getUserPosition(){
      var This = this
      // 实例化腾讯地图API核心类
      var qqmapsdk = new QQMapWX({
        key: 'DTYBZ-MNUCV-HQOP3-UD5FF-BLBQT-ATFI2' // 必填
      });
      //1、获取当前位置坐标
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success(addressRes) {
              var address = addressRes.result.ad_info.city.substring(0,addressRes.result.ad_info.city.length - 1);
              This.address = address;
              This.intSelectCity(address)
            }
          })
        }
      })
    },
    //初始化城市查询
    intSelectCity(city){
      if(city){
        this.page = 0; //page初始化
        this.selectType = 1;//根据类型判断分页
        this.reachBottomFlag = true;//初始化分页开关
        this.reqSelectCity(city);
      }
    },
    //根据城市进行搜索
    async reqSelectCity(city){
      var userToken = wx.getStorageSync('userToken');
      let params = {
        user_token: userToken,
        city: city,
        limit: this.limit,
        page:this.page,
      };
      let res = await getActivityList(params);
      if(res.data.level == "success"){
        wx.stopPullDownRefresh()
        let cityActivityList = res.data.activities;
        if(cityActivityList.length <= 0){
          this.reachBottomFlag = false; //如果没有数据了，上拉分页不再发送网络请求
        }else{
          if(params.page== 0){
            this.activityList = cityActivityList;
          }else{
            this.activityList = this.activityList.concat(cityActivityList);
          }
        }
      }else{
        wx.showToast({
          title: '获取活动列表失败',
          icon: 'none',
          duration: 1000
        })
      }
    },
    //跳转到全部活动方页面
    navgateToOrganizer(){
      wx.navigateTo({
        url: '/pages/organizer/main'
      })
    },
    //获取人气活动方列表
    async reqPopularityPartyList(){
      let params = {
        type: "popularity"
      }
      let res = await getPartyList(params);
      if(res.data.level == "success"){
        this.PartyList = res.data.data;
      }else{
        wx.showToast({
          title: '获取活动方人气列表失败',
          icon: 'none',
          duration: 1000
        })
      }
    },
    //跳活动方详情页面
    navigaToOrganizerIntro(Id){
      wx.navigateTo({
        url: '/pages/organizerIntro/main?id='+Id
      })
    },
  },
}
</script>

<style lang="stylus" scoped>
  .home
    width 100%
    background-color #f5f5f5
    .banner-box
      width 100%
      position relative
      .banner-box-top
        position absolute
        z-index 10
        left 50%
        top 20rpx
        width 90%
        display flex
        transform:translateX(-50%);
        .user-position
          display flex
          justify-content center
          align-items center
          font-size 14px
          color #888888
          .user-position-adress
            width 110rpx
            overflow: hidden;
            text-overflow:ellipsis;
            white-space: nowrap;
            color #000
          .user-position-icon
            width 38rpx
            height 38rpx
            background-repeat no-replace
            background-size 38rpx 38rpx
            background-position center center
            margin-right 4rpx
            margin-top 1rpx
            background-image url(../../../static/images/position1.png)
        .search
          flex 10
          position relative
          background-color #ccc
          box-sizing border-box
          padding-left 54rpx
          border-radius 10rpx
          height 50rpx
          opacity 0.7
          font-size 15px
          line-height 50rpx
          color #666
          .search-icon
            position absolute
            left 8rpx
            top 0
            width 50rpx
            height 50rpx
            background-image url(../../../static/images/magnifier.png)
            background-position center center
            background-size 50rpx 50rpx
      .swiper
        width 100%
        height 400rpx
      .banner-img
        width 100%
        height 400rpx
</style>
